package org.southyin.securitysamples.service;

import org.southyin.securitysamples.commons.CommonsResp;
import org.southyin.securitysamples.mapper.RoleMapper;
import org.southyin.securitysamples.mapper.UserMapper;
import org.southyin.securitysamples.model.Customer;
import org.southyin.securitysamples.model.Role;
import org.southyin.securitysamples.model.User;
import org.southyin.securitysamples.model.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;

    public List<UserBean> listUser(String keyWords) {
        return userMapper.listUser(keyWords);
    }

    public CommonsResp updateCustomer(UserBean userBean) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal.getId().equals(userBean.getId())) {
            return CommonsResp.failed(500,"不能修改自己");
        }
        int count = userMapper.updateCustomer(userBean);
        if (count == 0) {
            return CommonsResp.failed();
        }
        return CommonsResp.succeess();
    }

    public CommonsResp updateRole(UserBean userBean) {
        // 获取新角色 id
        List<Long> role = userBean.getRole();
        List<Role> roles = roleMapper.listRoles();
        // 超级管理员角色不能编辑，也不能新增超级管理员角色
        for (Role role1 : roles) {
            if (role1.getRname().equals("ROLE_admin")) {
                Long id = role1.getId();
                for (Long aLong : role) {
                    if (aLong.equals(id)) {
                        return CommonsResp.failed(500, "不能操作超级管理员");
                    }
                }
            }
        }
        // 获取user id
        Long id = userBean.getId();
        int count = roleMapper.isAdmin(id);
        if (count == 0) {
            if (role.size() == 0) {
                return CommonsResp.failed(500,"不能没有角色");
            }
            roleMapper.delRoles(id);
            roleMapper.insertRoles(id,role);
            return CommonsResp.succeess();
        }
        return CommonsResp.failed(500,"不能取消超级管理员角色");
    }
}
